
/**
 * 1. 是个构造函数
 * 2. 传入一个可执行函数 函数的入参第一个为 fullFill函数 第二个为 reject函数；  函数立即执行，  参数函数异步执行
 * 3. 状态一旦更改就不可以变更  只能 pending => fulfilled 或者  pending => rejected
 * 4. then 的时候要处理入参的情况 successCallback 和failCallback 均可能为非函数
 *      默认的 failCallback 一定要将异常抛出， 这样下一个promise便可将其捕获 异常冒泡的目的
 * 5. then 中执行回调的时候要捕获异常 将其传给下一个promise
 *    如果promise状态未变更 则将回调方法添加到对应队列中
 *    如果promise状态已经变更 需要异步处理成功或者失败回调
 *    因为可能出现 回调结果和当前then返回的Promise一致 从而导致死循环问题
 * 6. catch只是then的一种特殊的写法 方便理解和使用
 * 7. finally 特点 1. 不过resolve或者reject都会执行
 *                2. 回调没有参数
 *                3. 返回一个Promise 且值可以穿透到下一个then或者catch
 * 8. Promise.resolve, Promise.reject 根据其参数返回对应的值 或者状态的Promise即可
 * 9. Proise.all 特点  1. 返回一个Promise
 *                    2. 入参是数组 resolve的情况下出参也是数组 且结果顺序和调用顺序一致
 *                    3. 所有的值或者promise都完成才能resolve 所有要计数
 *                    4. 只要有一个为reject 返回的Promise便reject
 * 10. Proise.race 特点 1. 返回一个Promise
 *                     2. 入参是数组 那么出参根据第一个成功或者失败的参数来确定
 *                     3. 只要有一个resolve 或者reject 便更改返回Promise的状态
 *
 * 
 */
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
    //构造器
    constructor(executor) {
        //捕获执行器的错误
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e)
        }
    }
    //状态
    status = PENDING;
    //成功返回的值
    value = undefined;
    //失败返回的值
    reason = undefined;
    //成功回调
    successCallback = []
    //失败回调
    failCallback = []


    resolve = (value) => {
        if (this.status !== PENDING) return
        this.status = FULFILLED
        this.value = value
        //链式编程 逐个调用
        while (this.successCallback.length) this.successCallback.shift()()
    }
    reject = (reason) => {
        if (this.status !== PENDING) return
        this.status = REJECTED
        this.reason = reason
        //链式编程 逐个调用
        while (this.failCallback.length) this.failCallback.shift()()
    }
    then (successCallback, failCallback) {
        //参数可选
        successCallback = successCallback ? successCallback : value => value
        failCallback = failCallback ? failCallback : reason => { throw reason }
        let promise2 = new MyPromise((resolve, reject) => {
            //判断状态
            if (this.status === FULFILLED) {
                //捕捉错误
                setTimeout(() => {

                    try {
                        let x = successCallback(this.value)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0);

            } else if (this.status === REJECTED) {
                //捕捉错误
                setTimeout(() => {

                    try {
                        let x = failCallback(this.reason)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0);
            } else {
                //等待的时候把回调存储起来
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0);
                })
                //等待的时候把回调存储起来
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0);
                })
            }
        })
        return promise2
    }
    finally (callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value)
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }
    catch (failCallback) {
        return this.then(undefined, failCallback)
    }
    static all (array) {
        //接收结果数组
        let result = []
        let index = 0
        return new MyPromise((resolve, reject) => {
            function addData (key, value) {
                result[key] = value;
                index++;
                if (index === array.length) {
                    resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i]
                if (current instanceof MyPromise) {
                    //如果是promise对象 继续解析
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    //普通值
                    addData(i, current)
                }
            }
        })
    }
    static resolve (value) {
        if (value instanceof MyPromise) return value
        return new MyPromise(resolve => resolve(value))
    }
}

function resolvePromise (promise2, x, resolve, reject) {
    //自己不能调用自己
    if (promise2 === x) {
        return reject(new TypeError('my error promise'))
    }
    if (x instanceof MyPromise) {
        x.then(resolve, reject)
    } else {
        resolve(x)
    }
}


//test

const other = () => {
    return new MyPromise((resolve, reject) => {
        resolve('other')
    })
}


// let promise = new MyPromise((resolve, reject) => {
//     // throw new Error('executor error')
//     reject('失败')
//     // setTimeout(() => {
//     // resolve('成功')

//     // }, 2000);
// })

// promise.then(value => {
//     console.log(value);
//     // return other()
//     // throw new Error('then error')
//     return 'aaa'
// }, reason => {
//     console.log(reason);
//     return 10000
// }).then(value=>{
//     console.log(value);
// })

// let p1 = promise.then(value => {
//     console.log(value);
//     return p1
// })
// p1.then(value=>{
//     console.log(value);
// },reason=>{
//     console.log(reason.message); //拿对应的message
// })
// promise.then().then().then(value => console.log(value,'111'), reason => console.log(reason,'222'))

// test all
// function p1 () {
//     return new MyPromise(function (resolve, reject) {
//         setTimeout(() => {
//             resolve('hello');
//         }, 2000);
//     })
// }

// function p2 () {
//     return new MyPromise(function (resolve, reject) {
//         resolve('222');
//     })
// }
//   MyPromise.all(['a','b',p1(),p2(),'c']).then(result=>console.log(result))

// test resolve
// function p1 () {
//     return new MyPromise(function (resolve, reject) {
//         setTimeout(() => {
//             resolve('resolve');
//         }, 2000);
//     })
// }
// MyPromise.resolve(100).then(value=>console.log(value))
// MyPromise.resolve(p1()).then(value=>console.log(value))


// test finally
// function p1 () {
//     return new MyPromise(function (resolve, reject) {
//         setTimeout(() => {
//             resolve('p1');
//         }, 5000);
//     })
// }

// function p2 () {
//     return new MyPromise(function (resolve, reject) {
//         resolve('p2');
//     })
// }

// p2().finally(()=>{
//     console.log('finally');
//     return p1()
// }).then(value=>console.log(value),reason=>console.log(reason))

//test catch
// function p2 () {
//     return new MyPromise(function (resolve, reject) {
//         reject('reject')
//     })
// }
// p2().then(value => console.log(value)).catch(reason => console.log(reason))